import React, {
    Component,
    useCallback,
    useState,
    useEffect,
    useRef,
    useMemo,
} from "react";
import { useDispatch, useSelector } from "react-redux";
import { fromJS } from "immutable";
import Tab from "./Tab";
import { useHistory } from "react-router-dom";
import CountBar from "./CountBar";
import SkuBar from "./SkuBar";
import AppScroll from "../../app-scroll";
import closeIcon from "../../../assets/close.webp";
import { Modal } from "antd-mobile";
import "antd-mobile/dist/antd-mobile.css";

import "../style.scss";
export default function Panel({ onClose }) {
    const history = useHistory();
    //这里是要存储用户选择的信息
    const userSelectRef = useRef({});
    const dispatch = useDispatch();
    /*******************************************  开始向仓库获取数据 ****************************************/
    // 商品id
    const id = useSelector((state) => state.getIn(["detail", "data", "id"]));
    // 商品名称
    const name = useSelector((state) =>
        state.getIn(["detail", "data", "name"])
    );
    //图片
    const url = useSelector((state) =>
        state.getIn(["detail", "data", "primaryPicUrl"])
    );
    const [picUrl, setPicUrl] = useState(url);
    // 原价
    const oCounterPrice = useSelector((state) =>
        state.getIn(["detail", "data", "counterPrice"])
    );

    // 现价
    const oRetailPrice = useSelector((state) =>
        state.getIn(["detail", "data", "retailPrice"])
    );
    // 规格列表
    const skuList = useSelector((state) =>
        state.getIn(["detail", "data", "skuList"])
    );

    // 每一个规格搭配的信息
    const skuMap = useSelector((state) =>
        state.getIn(["detail", "data", "skuMap"])
    );
    // console.log(skuMap);
    // 用户选择的数量
    const [value, setValue] = useState(1);
    const [retailPrice, setRetailPrice] = useState(oRetailPrice);
    const [counterPrice, setCounterPrice] = useState(oCounterPrice);

    // 用户选择的规格
    // [颜色， 尺码]
    // [null, null]
    // 用户选择颜色和尺码 这部分应该存储格式为数组
    const [selectedArr, setSeletedctArr] = useState(() => {
        const temp = new Array(skuList.size).fill(null);
        return fromJS(temp);
    });

    // 计算用户选择的所有信息

    const selectedInfo = useMemo(() => {
        const ids = selectedArr.map((item) => (item ? item.get("id") : ""));
        const key = ids.join(";");
        return skuMap.get(key);
    }, [selectedArr, skuMap]);

    useEffect(() => {
        if (selectedInfo) {
            setPicUrl(selectedInfo.get("pic") || url);
            setCounterPrice(selectedInfo.get("counterPrice") || oCounterPrice);
            setRetailPrice(selectedInfo.get("retailPrice") || oRetailPrice);
        } else {
            setPicUrl(url);
            setCounterPrice(oCounterPrice);
            setRetailPrice(oRetailPrice);
        }
    }, [selectedInfo, url, oCounterPrice, oRetailPrice]);

    //处理用户选择的功能函数
    const selectedAction = useCallback(
        (title, item) => {
            // 规格分为颜色尺码等等 在skuList中找到是第几个
            const index = skuList.findIndex(
                (item) => item.get("name") === title
            );
            // 为了不依赖于 selectedArr，故而写成一个函数的形式
            setSeletedctArr((selectedArr) => selectedArr.set(index, item));
        },
        [skuList]
    );

    // 处理数量的变化事件
    const onValueChange = useCallback((newValue) => {
        let temp = parseInt(newValue);
        if (temp > 0) {
            setValue(temp);
        } else {
            //引入antd至少一件起售
            Modal.alert("至少一件起售");
        }
    }, []);
    useEffect(() => {
        userSelectRef.current = {
            id,
            count: value,
            selected: selectedArr,
            skuList,
            selectedInfo,
            name,
            picUrl,
            counterPrice,
            retailPrice,
        };
    }, [
        value,
        selectedArr,
        skuList,
        selectedInfo,
        id,
        name,
        picUrl,
        counterPrice,
        retailPrice,
    ]);
    // 在加入购物车前，需要判断参数是否完整
    const checkCanNext = () => {
        const skuList = userSelectRef.current.skuList;
        const arr = userSelectRef.current.selected;
        const index = arr.findIndex((item) => item === null);
        if (index >= 0) {
            Modal.alert("请选择" + skuList.getIn([index, "name"]));
            return false;
        } else {
            return true;
        }
    };
    //添加商品进入购物车
    const onAddCartAction = useCallback(() => {
        if (checkCanNext()) {
            const selected = userSelectRef.current.selected;
            const count = userSelectRef.current.count;
            const id = userSelectRef.current.id;
            const name = userSelectRef.current.name;
            const picUrl = userSelectRef.current.picUrl;
            const counterPrice = userSelectRef.current.counterPrice;
            const retailPrice = userSelectRef.current.retailPrice;
            dispatch({
                type: "user/add_goods_to_car",
                payload: {
                    goodsId: id,
                    count,
                    name,
                    picUrl,
                    counterPrice,
                    retailPrice,
                    selected: selected.toJS(), //这是一个immutable参数，传值需要先转化为普通参数
                },
            });
            const tag=sessionStorage.getItem('addCar')
            if(tag){
                Modal.alert("加入成功");
            }else{
                Modal.alert("加入失败");

            }
            

        }
    }, [dispatch]);
    const onBuyAction = useCallback(() => {});
    return (
        <div className="detail-panel">
            <div className="cover" onClick={onClose}>
                {/* 这里的空标签是为了显示这个组件时不能点击主页面的其他的东西，故而这里也要设置全屏显示 */}
            </div>
            <button className="close-btn" onClick={onClose}>
                <img src={closeIcon} alt="" />
            </button>
            <AppScroll className="panel-wrap">
                <div className="top">
                    <div className="top-img">
                        <img className="primary-pic-url" src={picUrl} alt="" />
                    </div>
                    <div className="top-info">
                        <p>
                            <span>价格：</span>
                            <span>￥{retailPrice}</span>
                            {counterPrice && (
                                <span>
                                    {retailPrice === counterPrice ||
                                        "￥" + counterPrice}
                                </span>
                            )}
                        </p>
                        <p>
                            <span>已选择：</span>
                            <span>
                                {selectedArr.filter((item) => item).size > 0
                                    ? selectedArr
                                          .filter((item) => item)
                                          .map((item) => item.get("value"))
                                          .toJS()
                                          .join(" ")
                                    : "请选择规格数量"}
                            </span>
                        </p>
                    </div>
                </div>
                {skuList.map((item) => {
                    return (
                        <SkuBar
                            key={item.get("id")}
                            title={item.get("name")}
                            list={item.get("skuSpecValueList")}
                            onSelected={selectedAction}
                        />
                    );
                })}
                <CountBar value={value} onValueChange={onValueChange} />
            </AppScroll>
            <Tab onAddCart={onAddCartAction} onBuy={onBuyAction} />
        </div>
    );
}
